/**
 * BookmarkManager - 收藏管理器
 * 负责收藏的增删改查、搜索、渲染等功能
 */

class BookmarkManager {
    constructor(apiService) {
        this.api = apiService;
        this.bookmarks = [];
        this.currentFilter = {
            categoryId: '',
            searchQuery: ''
        };
        this.batchMode = false;
        this.selectedBookmarks = new Set();
        this.sortableInstance = null;
        this.isDragging = false;
    }

    /**
     * 加载收藏列表
     */
    async loadBookmarks() {
        try {
            // 设置limit为1000，确保加载所有收藏
            const response = await this.api.getBookmarks({ limit: 1000 });
            if (response.success) {
                this.bookmarks = response.data.bookmarks || [];
                console.log('收藏数据加载成功:', this.bookmarks.length, '个收藏');
                return this.bookmarks;
            } else {
                showNotification('加载收藏失败', 'error');
                return [];
            }
        } catch (error) {
            console.error('加载收藏出错:', error);
            showNotification('网络错误，请稍后重试', 'error');
            return [];
        }
    }

    /**
     * 添加收藏
     */
    async addBookmark(name, url, categoryId = null) {
        if (!name || !url) {
            showNotification('请填写完整的网站名称和链接', 'error');
            return false;
        }

        // 验证URL格式
        if (!isValidUrl(url)) {
            showNotification('请输入有效的网址格式', 'error');
            return false;
        }

        try {
            const response = await this.api.createBookmark(name, url, categoryId);
            if (response.success) {
                this.bookmarks.unshift(response.data.bookmark);
                showNotification('收藏添加成功！', 'success');
                return response.data.bookmark;
            } else {
                showNotification(response.message || '收藏添加失败', 'error');
                return false;
            }
        } catch (error) {
            showNotification('网络错误，请稍后重试', 'error');
            return false;
        }
    }

    /**
     * 删除收藏
     */
    async deleteBookmark(id) {
        const bookmark = this.bookmarks.find(b => b.id === id);
        if (!bookmark) {
            showNotification('收藏不存在', 'error');
            return false;
        }

        // 创建确认对话框
        return new Promise((resolve) => {
            const modal = document.createElement('div');
            modal.className = 'modal';
            modal.innerHTML = `
                <div class="modal-content">
                    <div class="modal-header">
                        <h3><i class="fas fa-trash"></i> 删除收藏</h3>
                        <span class="close" onclick="this.closest('.modal').remove()">&times;</span>
                    </div>
                    <div class="modal-body">
                        <p>确定要删除收藏 "<strong>${escapeHtml(bookmark.name)}</strong>" 吗？</p>
                        <p class="warning-text">
                            <i class="fas fa-exclamation-triangle"></i>
                            此操作不可撤销！
                        </p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" onclick="this.closest('.modal').remove()">取消</button>
                        <button type="button" class="btn btn-danger" id="confirmDeleteBtn">确认删除</button>
                    </div>
                </div>
            `;

            document.body.appendChild(modal);
            modal.style.display = 'block';

            document.getElementById('confirmDeleteBtn').onclick = async () => {
                try {
                    const response = await this.api.deleteBookmark(id);
                    if (response && response.success) {
                        const index = this.bookmarks.findIndex(b => b.id === id);
                        if (index !== -1) {
                            this.bookmarks.splice(index, 1);
                        }
                        modal.remove();
                        showNotification(response.message || '收藏删除成功！', 'success');
                        resolve(true);
                    } else {
                        showNotification(response?.message || '删除失败', 'error');
                        modal.remove();
                        resolve(false);
                    }
                } catch (error) {
                    console.error('删除出错:', error);
                    showNotification('网络错误，请稍后重试', 'error');
                    modal.remove();
                    resolve(false);
                }
            };
        });
    }

    /**
     * 移动收藏到分组
     */
    async moveBookmark(id, newCategoryId) {
        try {
            const response = await this.api.moveBookmark(id, newCategoryId);
            if (response.success) {
                const index = this.bookmarks.findIndex(b => b.id === id);
                if (index !== -1) {
                    // 更新本地数据
                    this.bookmarks[index] = response.data.bookmark;
                }
                showNotification('收藏移动成功！', 'success');
                return true;
            } else {
                showNotification(response.message || '移动失败', 'error');
                return false;
            }
        } catch (error) {
            showNotification('网络错误，请稍后重试', 'error');
            return false;
        }
    }

    /**
     * 显示移动收藏对话框
     */
    showMoveDialog(id, categories) {
        const bookmark = this.bookmarks.find(b => b.id === id);
        if (!bookmark) return;

        // 获取分组列表 - 尝试多种方式
        if (!categories || categories.length === 0) {
            if (typeof categoryManager !== 'undefined' && categoryManager) {
                categories = categoryManager.categories || [];
            } else if (window.categoryManager) {
                categories = window.categoryManager.categories || [];
            } else if (typeof navigationManager !== 'undefined' && navigationManager) {
                categories = navigationManager.categoryManager.categories || [];
            } else {
                categories = [];
            }
        }

        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.id = 'moveBookmarkModal';
        modal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h3><i class="fas fa-arrows-alt"></i> 移动收藏</h3>
                    <button class="modal-close" onclick="this.parentElement.parentElement.parentElement.remove()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="bookmark-info">
                        <h4>${escapeHtml(bookmark.name)}</h4>
                        <p class="text-muted">${escapeHtml(bookmark.url)}</p>
                        <p class="current-category">
                            当前分组: ${bookmark.category_name ? 
                                `<span class="category-badge" style="background-color: ${bookmark.category_color}">
                                    <i class="${bookmark.category_icon}"></i> ${bookmark.category_name}
                                </span>` : 
                                '<span class="text-muted">未分组</span>'}
                        </p>
                    </div>
                    <div class="form-group">
                        <label>移动到分组:</label>
                        <select id="moveToCategory" class="category-select">
                            <option value="">未分组</option>
                            ${categories.map(category => `
                                <option value="${category.id}" ${bookmark.category_id == category.id ? 'selected' : ''}>
                                    ${escapeHtml(category.name)}
                                </option>
                            `).join('')}
                        </select>
                    </div>
                    ${categories.length === 0 ? '<p style="color: #999; margin-top: 10px; font-size: 0.9rem;">提示：请先创建分组</p>' : ''}
                    <div class="modal-buttons">
                        <button id="confirmMoveBtn" class="btn-primary">
                            <i class="fas fa-check"></i> 确认移动
                        </button>
                        <button onclick="this.parentElement.parentElement.parentElement.parentElement.remove()" class="btn-secondary">
                            取消
                        </button>
                    </div>
                </div>
            </div>
        `;

        document.body.appendChild(modal);
        modal.style.display = 'block';

        document.getElementById('confirmMoveBtn').onclick = async () => {
            const categorySelect = document.getElementById('moveToCategory');
            const newCategoryId = categorySelect.value || null;
            const success = await this.moveBookmark(id, newCategoryId);
            if (success) {
                modal.remove();
                // 触发事件通知需要刷新
                window.dispatchEvent(new CustomEvent('bookmarkMoved'));
            }
        };
    }

    /**
     * 按分组筛选
     */
    filterByCategory(categoryId) {
        this.currentFilter.categoryId = categoryId;
        return this.getFilteredBookmarks();
    }

    /**
     * 搜索收藏
     */
    searchBookmarks(query) {
        this.currentFilter.searchQuery = query.toLowerCase();
        return this.getFilteredBookmarks();
    }

    /**
     * 获取筛选后的收藏
     */
    getFilteredBookmarks() {
        let filtered = [...this.bookmarks];

        // 按分组筛选
        if (this.currentFilter.categoryId) {
            filtered = filtered.filter(b => 
                b.category_id && b.category_id.toString() === this.currentFilter.categoryId
            );
        }

        // 按搜索词筛选
        if (this.currentFilter.searchQuery) {
            filtered = filtered.filter(b => {
                const name = b.name.toLowerCase();
                const url = b.url.toLowerCase();
                return name.includes(this.currentFilter.searchQuery) || 
                       url.includes(this.currentFilter.searchQuery);
            });
        }

        // 如果没有搜索，按sort_order排序
        if (!this.currentFilter.searchQuery) {
            filtered.sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0));
        }

        return filtered;
    }

    /**
     * 渲染收藏列表
     */
    renderBookmarks(containerId = 'bookmarksList') {
        const container = document.getElementById(containerId);
        if (!container) return;

        const filtered = this.getFilteredBookmarks();

        if (filtered.length === 0) {
            if (this.bookmarks.length === 0) {
                container.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-bookmark"></i>
                        <h3>还没有收藏任何网站</h3>
                        <p>添加你第一个收藏的网站吧！</p>
                    </div>
                `;
            } else if (this.currentFilter.searchQuery) {
                container.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-search"></i>
                        <h3>未找到匹配的收藏</h3>
                        <p>没有找到包含 "${escapeHtml(this.currentFilter.searchQuery)}" 的收藏项</p>
                    </div>
                `;
            } else {
                container.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-filter"></i>
                        <h3>该分组中还没有收藏</h3>
                        <p>尝试添加一些收藏到这个分组中</p>
                    </div>
                `;
            }
            return;
        }

        container.innerHTML = filtered.map(bookmark => {
            const isSelected = this.selectedBookmarks.has(bookmark.id);
            return `
            <div class="bookmark-item ${this.batchMode ? 'batch-mode' : ''} ${isSelected ? 'selected' : ''}" data-id="${bookmark.id}" data-category-id="${bookmark.category_id || ''}">
                ${this.batchMode ? `
                    <div class="bookmark-checkbox-wrapper">
                        <input type="checkbox" 
                               class="bookmark-checkbox" 
                               data-id="${bookmark.id}"
                               ${isSelected ? 'checked' : ''}
                               onchange="bookmarkManager.toggleBookmarkSelection(${bookmark.id})">
                    </div>
                ` : ''}
                <div class="bookmark-actions ${this.batchMode ? 'hidden' : ''}">
                    <button class="edit-btn" onclick="bookmarkManager.showEditDialog(${bookmark.id})" title="编辑收藏">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="move-btn" onclick="bookmarkManager.showMoveDialog(${bookmark.id}, categoryManager.categories)" title="移动到分组">
                        <i class="fas fa-arrows-alt"></i>
                    </button>
                    <button class="delete-btn" onclick="bookmarkManager.deleteAndRefresh(${bookmark.id})" title="删除收藏">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
                <div class="bookmark-content" onclick="${this.batchMode ? `bookmarkManager.toggleBookmarkSelection(${bookmark.id})` : `openWebsite('${bookmark.url}')`}">
                    <div class="bookmark-title">
                        <img src="${bookmark.favicon || getFaviconUrl(bookmark.url)}" alt="favicon" width="16" height="16" onerror="this.style.display='none'">
                        <span>${escapeHtml(bookmark.name)}</span>
                    </div>
                    <div class="bookmark-url">${escapeHtml(bookmark.url)}</div>
                    <div class="bookmark-meta">
                        <span>添加时间：${formatDate(bookmark.created_at)}</span>
                        <span><i class="fas fa-external-link-alt"></i></span>
                    </div>
                </div>
            </div>
        `;
        }).join('');

        // 初始化拖拽排序（非批量模式且非搜索状态）
        if (!this.batchMode && !this.currentFilter.searchQuery) {
            this.initializeSortable();
        }
    }

    /**
     * 初始化拖拽排序
     */
    initializeSortable() {
        const container = document.getElementById('bookmarksList');
        if (!container || !window.Sortable) return;

        // 销毁已存在的实例
        if (this.sortableInstance) {
            this.sortableInstance.destroy();
        }

        // 创建新的拖拽实例
        this.sortableInstance = Sortable.create(container, {
            animation: 150,
            handle: '.bookmark-item',
            ghostClass: 'sortable-ghost',
            chosenClass: 'sortable-chosen',
            dragClass: 'sortable-drag',
            disabled: this.batchMode,
            
            onStart: () => {
                this.isDragging = true;
            },
            
            onEnd: async (evt) => {
                this.isDragging = false;
                
                if (evt.oldIndex !== evt.newIndex) {
                    // 更新本地数组顺序
                    const filtered = this.getFilteredBookmarks();
                    const movedItem = filtered[evt.oldIndex];
                    filtered.splice(evt.oldIndex, 1);
                    filtered.splice(evt.newIndex, 0, movedItem);
                    
                    // 更新sort_order
                    await this.saveSortOrder(filtered);
                }
            }
        });
    }

    /**
     * 保存排序顺序
     */
    async saveSortOrder(orderedBookmarks) {
        try {
            // 批量更新sort_order
            const updates = orderedBookmarks.map((bookmark, index) => ({
                id: bookmark.id,
                sort_order: index
            }));

            // 逐个更新（可以优化为批量API）
            for (const update of updates) {
                const bookmark = this.bookmarks.find(b => b.id === update.id);
                if (bookmark && bookmark.sort_order !== update.sort_order) {
                    await this.api.updateBookmark(update.id, { 
                        sort_order: update.sort_order 
                    });
                    bookmark.sort_order = update.sort_order;
                }
            }

            showNotification('排序已保存', 'success');
        } catch (error) {
            console.error('保存排序失败:', error);
            showNotification('保存排序失败', 'error');
            // 重新加载以恢复原顺序
            await this.loadBookmarks();
            this.renderBookmarks();
        }
    }

    /**
     * 删除并刷新（辅助方法）
     */
    async deleteAndRefresh(id) {
        const success = await this.deleteBookmark(id);
        if (success) {
            this.renderBookmarks();
            this.updateStats();
            // 通知分组管理器更新计数
            window.dispatchEvent(new CustomEvent('bookmarkDeleted'));
        }
    }

    /**
     * 显示编辑收藏对话框
     */
    showEditDialog(id) {
        const bookmark = this.bookmarks.find(b => b.id === id);
        if (!bookmark) return;

        let modal = document.getElementById('editBookmarkModal');
        if (!modal) {
            modal = document.createElement('div');
            modal.id = 'editBookmarkModal';
            modal.className = 'modal';
            document.body.appendChild(modal);
        }

        modal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h3><i class="fas fa-edit"></i> 编辑收藏</h3>
                    <button class="modal-close" onclick="document.getElementById('editBookmarkModal').style.display='none'">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>网站名称 <span class="required">*</span></label>
                        <input type="text" id="editBookmarkName" value="${escapeHtml(bookmark.name)}" maxlength="255" required>
                    </div>
                    <div class="form-group">
                        <label>网站地址 <span class="required">*</span></label>
                        <input type="url" id="editBookmarkUrl" value="${escapeHtml(bookmark.url)}" required>
                    </div>
                    <div class="form-group">
                        <label>描述/备注</label>
                        <textarea id="editBookmarkDescription" rows="3" maxlength="1000" placeholder="添加一些备注信息...">${escapeHtml(bookmark.description || '')}</textarea>
                    </div>
                    <div class="modal-buttons">
                        <button id="saveEditBookmarkBtn" class="btn-primary">
                            <i class="fas fa-save"></i> 保存
                        </button>
                        <button onclick="document.getElementById('editBookmarkModal').style.display='none'" class="btn-secondary">
                            取消
                        </button>
                    </div>
                </div>
            </div>
        `;

        modal.style.display = 'block';

        // 绑定保存按钮事件
        document.getElementById('saveEditBookmarkBtn').onclick = () => this.handleSaveEditBookmark(id);
    }

    /**
     * 处理保存编辑
     */
    async handleSaveEditBookmark(id) {
        const nameInput = document.getElementById('editBookmarkName');
        const urlInput = document.getElementById('editBookmarkUrl');
        const descInput = document.getElementById('editBookmarkDescription');

        if (!nameInput || !urlInput) return;

        const data = {
            name: nameInput.value.trim(),
            url: urlInput.value.trim(),
            description: descInput ? descInput.value.trim() : ''
        };

        if (!data.name || !data.url) {
            showNotification('请填写网站名称和地址', 'error');
            return;
        }

        const success = await this.updateBookmark(id, data);
        if (success) {
            const modal = document.getElementById('editBookmarkModal');
            if (modal) modal.style.display = 'none';
            
            // 刷新显示
            this.renderBookmarks();
            window.dispatchEvent(new CustomEvent('bookmarkUpdated'));
        }
    }

    /**
     * 更新收藏
     */
    async updateBookmark(id, data) {
        try {
            const response = await this.api.updateBookmark(id, data);
            if (response.success) {
                const index = this.bookmarks.findIndex(b => b.id === id);
                if (index !== -1) {
                    this.bookmarks[index] = response.data.bookmark;
                }
                showNotification('收藏更新成功！', 'success');
                return true;
            } else {
                showNotification(response.message || '更新失败', 'error');
                return false;
            }
        } catch (error) {
            showNotification('网络错误，请稍后重试', 'error');
            return false;
        }
    }

    /**
     * 更新统计信息
     */
    updateStats() {
        const countElement = document.getElementById('bookmarkCount');
        if (countElement) {
            countElement.textContent = this.bookmarks.length;
        }
    }

    /**
     * 获取收藏数量
     */
    getCount() {
        return this.bookmarks.length;
    }

    /**
     * 分析用户兴趣（用于智能推荐）
     */
    analyzeUserInterests() {
        const interests = {
            efficiency: 0,
            learning: 0,
            development: 0,
            design: 0
        };

        this.bookmarks.forEach(bookmark => {
            const text = (bookmark.name + ' ' + bookmark.url).toLowerCase();
            
            if (text.match(/(notion|todoist|productivity|task|note|manage|calendar|time)/)) {
                interests.efficiency++;
            }
            if (text.match(/(course|learn|study|education|tutorial|mooc|university)/)) {
                interests.learning++;
            }
            if (text.match(/(github|code|dev|program|api|tech|stack|js|python|react)/)) {
                interests.development++;
            }
            if (text.match(/(design|figma|photoshop|ui|ux|creative|color|font)/)) {
                interests.design++;
            }
        });

        return interests;
    }

    /**
     * 导出数据为JSON格式
     */
    exportToJSON() {
        const data = {
            exportDate: new Date().toISOString(),
            version: '1.0',
            totalBookmarks: this.bookmarks.length,
            bookmarks: this.bookmarks.map(b => ({
                id: b.id,
                name: b.name,
                url: b.url,
                description: b.description || '',
                category: b.category_name || '未分组',
                categoryId: b.category_id,
                createdAt: b.created_at,
                updatedAt: b.updated_at
            }))
        };

        const jsonStr = JSON.stringify(data, null, 2);
        const blob = new Blob([jsonStr], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        
        const a = document.createElement('a');
        a.href = url;
        a.download = `bookmarks_${new Date().toISOString().split('T')[0]}.json`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        
        showNotification('数据已导出为JSON格式', 'success');
    }

    /**
     * 导出数据为HTML Netscape书签格式
     */
    exportToHTML() {
        // 按分组组织书签
        const grouped = {};
        this.bookmarks.forEach(bookmark => {
            const category = bookmark.category_name || '未分组';
            if (!grouped[category]) {
                grouped[category] = [];
            }
            grouped[category].push(bookmark);
        });

        // 生成HTML
        let html = `<!DOCTYPE NETSCAPE-Bookmark-file-1>
<!-- This is an automatically generated file.
     It will be read and overwritten.
     DO NOT EDIT! -->
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<TITLE>Bookmarks</TITLE>
<H1>Bookmarks</H1>
<DL><p>\n`;

        Object.keys(grouped).forEach(category => {
            html += `    <DT><H3>${escapeHtml(category)}</H3>\n`;
            html += `    <DL><p>\n`;
            
            grouped[category].forEach(bookmark => {
                const timestamp = new Date(bookmark.created_at).getTime() / 1000;
                html += `        <DT><A HREF="${escapeHtml(bookmark.url)}" ADD_DATE="${Math.floor(timestamp)}">${escapeHtml(bookmark.name)}</A>\n`;
                if (bookmark.description) {
                    html += `        <DD>${escapeHtml(bookmark.description)}\n`;
                }
            });
            
            html += `    </DL><p>\n`;
        });

        html += `</DL><p>\n`;

        const blob = new Blob([html], { type: 'text/html' });
        const url = URL.createObjectURL(blob);
        
        const a = document.createElement('a');
        a.href = url;
        a.download = `bookmarks_${new Date().toISOString().split('T')[0]}.html`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        
        showNotification('数据已导出为HTML书签格式', 'success');
    }

    /**
     * 导出数据为CSV格式
     */
    exportToCSV() {
        // CSV头部
        let csv = '名称,网址,描述,分组,创建时间\n';
        
        // 添加数据行
        this.bookmarks.forEach(bookmark => {
            const name = `"${(bookmark.name || '').replace(/"/g, '""')}"`;
            const url = `"${(bookmark.url || '').replace(/"/g, '""')}"`;
            const description = `"${(bookmark.description || '').replace(/"/g, '""')}"`;
            const category = `"${(bookmark.category_name || '未分组').replace(/"/g, '""')}"`;
            const createdAt = bookmark.created_at || '';
            
            csv += `${name},${url},${description},${category},${createdAt}\n`;
        });

        const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        
        const a = document.createElement('a');
        a.href = url;
        a.download = `bookmarks_${new Date().toISOString().split('T')[0]}.csv`;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
        
        showNotification('数据已导出为CSV格式', 'success');
    }

    /**
     * 显示导出选项对话框
     */
    showExportDialog() {
        let modal = document.getElementById('exportModal');
        if (!modal) {
            modal = document.createElement('div');
            modal.id = 'exportModal';
            modal.className = 'modal';
            document.body.appendChild(modal);
        }

        modal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h3><i class="fas fa-download"></i> 导出收藏数据</h3>
                    <button class="modal-close" onclick="document.getElementById('exportModal').style.display='none'">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="modal-body">
                    <p class="modal-description">选择要导出的格式：</p>
                    <div class="export-options">
                        <button class="export-option-btn" onclick="bookmarkManager.exportToJSON(); document.getElementById('exportModal').style.display='none'">
                            <i class="fas fa-file-code"></i>
                            <div class="export-option-info">
                                <h4>JSON 格式</h4>
                                <p>包含完整数据，适合备份和迁移</p>
                            </div>
                        </button>
                        <button class="export-option-btn" onclick="bookmarkManager.exportToHTML(); document.getElementById('exportModal').style.display='none'">
                            <i class="fas fa-file-code"></i>
                            <div class="export-option-info">
                                <h4>HTML 书签格式</h4>
                                <p>Netscape格式，可导入浏览器</p>
                            </div>
                        </button>
                        <button class="export-option-btn" onclick="bookmarkManager.exportToCSV(); document.getElementById('exportModal').style.display='none'">
                            <i class="fas fa-file-excel"></i>
                            <div class="export-option-info">
                                <h4>CSV 格式</h4>
                                <p>表格格式，可用Excel打开</p>
                            </div>
                        </button>
                    </div>
                    <div class="export-stats">
                        <p><i class="fas fa-info-circle"></i> 当前共有 <strong>${this.bookmarks.length}</strong> 个收藏</p>
                    </div>
                </div>
            </div>
        `;

        modal.style.display = 'block';
    }

    // ========== 导入功能 ==========

    /**
     * 显示导入对话框
     */
    showImportDialog() {
        let modal = document.getElementById('importModal');
        if (!modal) {
            modal = document.createElement('div');
            modal.id = 'importModal';
            modal.className = 'modal';
            document.body.appendChild(modal);
        }

        // 获取分组列表
        let categories = [];
        if (typeof categoryManager !== 'undefined' && categoryManager) {
            categories = categoryManager.categories || [];
        } else if (window.categoryManager) {
            categories = window.categoryManager.categories || [];
        }

        modal.innerHTML = `
            <div class="modal-content import-modal">
                <div class="modal-header">
                    <h3><i class="fas fa-file-upload"></i> 导入收藏</h3>
                    <button class="modal-close" onclick="document.getElementById('importModal').style.display='none'">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="import-step" id="importStep1">
                        <h4>步骤 1: 选择文件</h4>
                        <p class="modal-description">支持的格式：HTML书签文件、JSON、CSV</p>
                        
                        <div class="file-upload-area" id="fileUploadArea">
                            <i class="fas fa-cloud-upload-alt"></i>
                            <p>点击选择文件或拖拽到此处</p>
                            <input type="file" id="importFileInput" accept=".html,.htm,.json,.csv" style="display: none;">
                            <button class="btn-primary" onclick="document.getElementById('importFileInput').click()">
                                <i class="fas fa-folder-open"></i> 选择文件
                            </button>
                        </div>
                        
                        <div class="file-info" id="fileInfo" style="display: none;">
                            <div class="file-details">
                                <i class="fas fa-file"></i>
                                <div>
                                    <strong id="fileName"></strong>
                                    <p id="fileSize"></p>
                                </div>
                                <button class="btn-small" onclick="bookmarkManager.clearImportFile()">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                        </div>
                        
                        <div class="import-tips">
                            <h5><i class="fas fa-lightbulb"></i> 提示</h5>
                            <ul>
                                <li><strong>HTML格式：</strong>从浏览器导出的书签文件（Netscape格式）</li>
                                <li><strong>JSON格式：</strong>从本系统导出的JSON文件或标准JSON数组</li>
                                <li><strong>CSV格式：</strong>包含"名称,网址,描述,分组"列的CSV文件</li>
                            </ul>
                        </div>
                    </div>
                    
                    <div class="import-step" id="importStep2" style="display: none;">
                        <h4>步骤 2: 预览和配置</h4>
                        
                        <div class="import-summary" id="importSummary"></div>
                        
                        <div class="import-options">
                            <div class="form-group">
                                <label>
                                    <input type="checkbox" id="skipDuplicates" checked>
                                    跳过重复的网址
                                </label>
                            </div>
                            
                            <div class="form-group">
                                <label>导入到分组：</label>
                                <select id="targetCategory" class="category-select">
                                    <option value="">保持原分组（自动创建不存在的分组）</option>
                                    ${categories.map(cat => `
                                        <option value="${cat.id}">${escapeHtml(cat.name)}</option>
                                    `).join('')}
                                </select>
                            </div>
                        </div>
                        
                        <div class="import-preview" id="importPreview">
                            <h5>数据预览（前10条）</h5>
                            <div class="preview-list" id="previewList"></div>
                        </div>
                        
                        <div class="modal-buttons">
                            <button class="btn-primary" onclick="bookmarkManager.executeImport()">
                                <i class="fas fa-check"></i> 开始导入
                            </button>
                            <button class="btn-secondary" onclick="bookmarkManager.showImportStep(1)">
                                <i class="fas fa-arrow-left"></i> 返回
                            </button>
                        </div>
                    </div>
                    
                    <div class="import-step" id="importStep3" style="display: none;">
                        <h4>导入完成</h4>
                        <div class="import-result" id="importResult"></div>
                        <div class="modal-buttons">
                            <button class="btn-primary" onclick="bookmarkManager.finishImport()">
                                <i class="fas fa-check"></i> 完成
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        `;

        modal.style.display = 'block';

        // 绑定文件选择事件
        const fileInput = document.getElementById('importFileInput');
        fileInput.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                this.handleImportFile(e.target.files[0]);
            }
        });

        // 拖拽上传
        const uploadArea = document.getElementById('fileUploadArea');
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('drag-over');
        });
        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('drag-over');
        });
        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('drag-over');
            if (e.dataTransfer.files.length > 0) {
                this.handleImportFile(e.dataTransfer.files[0]);
            }
        });
    }

    /**
     * 处理导入文件
     */
    async handleImportFile(file) {
        try {
            // 显示文件信息
            document.getElementById('fileName').textContent = file.name;
            document.getElementById('fileSize').textContent = this.formatFileSize(file.size);
            document.getElementById('fileInfo').style.display = 'block';

            // 解析文件
            showNotification('正在解析文件...', 'info');
            const response = await this.api.parseImportFile(file);

            if (response.success) {
                this.importData = response.data;
                showNotification(`解析成功！找到 ${response.data.total} 个书签`, 'success');
                this.showImportStep(2);
                this.displayImportPreview();
            } else {
                showNotification(response.message || '文件解析失败', 'error');
            }
        } catch (error) {
            console.error('解析文件失败:', error);
            showNotification('文件解析失败，请检查文件格式', 'error');
        }
    }

    /**
     * 显示导入预览
     */
    displayImportPreview() {
        if (!this.importData) return;

        const { bookmarks, total, duplicates, new: newCount } = this.importData;

        // 显示统计信息
        const summary = document.getElementById('importSummary');
        summary.innerHTML = `
            <div class="import-stats">
                <div class="stat-item">
                    <i class="fas fa-bookmark"></i>
                    <div>
                        <strong>${total}</strong>
                        <span>总数</span>
                    </div>
                </div>
                <div class="stat-item">
                    <i class="fas fa-plus-circle" style="color: #52c41a;"></i>
                    <div>
                        <strong>${newCount}</strong>
                        <span>新增</span>
                    </div>
                </div>
                <div class="stat-item">
                    <i class="fas fa-copy" style="color: #faad14;"></i>
                    <div>
                        <strong>${duplicates}</strong>
                        <span>重复</span>
                    </div>
                </div>
            </div>
        `;

        // 显示预览列表（前10条）
        const previewList = document.getElementById('previewList');
        const preview = bookmarks.slice(0, 10);
        
        previewList.innerHTML = preview.map((bookmark, index) => `
            <div class="preview-item ${bookmark.is_duplicate ? 'duplicate' : ''}">
                <div class="preview-number">${index + 1}</div>
                <div class="preview-content">
                    <div class="preview-name">${escapeHtml(bookmark.name)}</div>
                    <div class="preview-url">${escapeHtml(bookmark.url)}</div>
                    ${bookmark.folder ? `<div class="preview-folder"><i class="fas fa-folder"></i> ${escapeHtml(bookmark.folder)}</div>` : ''}
                </div>
                ${bookmark.is_duplicate ? '<span class="duplicate-badge">重复</span>' : ''}
            </div>
        `).join('');

        if (bookmarks.length > 10) {
            previewList.innerHTML += `<p class="preview-more">... 还有 ${bookmarks.length - 10} 条</p>`;
        }
    }

    /**
     * 执行导入
     */
    async executeImport() {
        if (!this.importData) return;

        const skipDuplicates = document.getElementById('skipDuplicates').checked;
        const targetCategory = document.getElementById('targetCategory').value || null;

        try {
            showNotification('正在导入...', 'info');
            
            const response = await this.api.importBookmarks(
                this.importData.bookmarks,
                targetCategory,
                skipDuplicates
            );

            if (response.success) {
                const { imported, skipped, failed, total } = response.data;
                
                // 显示结果
                const resultDiv = document.getElementById('importResult');
                resultDiv.innerHTML = `
                    <div class="import-success">
                        <i class="fas fa-check-circle"></i>
                        <h4>导入完成！</h4>
                        <div class="import-result-stats">
                            <div class="result-stat success">
                                <strong>${imported}</strong>
                                <span>成功导入</span>
                            </div>
                            <div class="result-stat warning">
                                <strong>${skipped}</strong>
                                <span>跳过重复</span>
                            </div>
                            ${failed > 0 ? `
                                <div class="result-stat error">
                                    <strong>${failed}</strong>
                                    <span>导入失败</span>
                                </div>
                            ` : ''}
                        </div>
                    </div>
                `;

                this.showImportStep(3);
                showNotification(`成功导入 ${imported} 个书签`, 'success');
            } else {
                showNotification(response.message || '导入失败', 'error');
            }
        } catch (error) {
            console.error('导入失败:', error);
            showNotification('导入失败，请重试', 'error');
        }
    }

    /**
     * 切换导入步骤
     */
    showImportStep(step) {
        for (let i = 1; i <= 3; i++) {
            const stepDiv = document.getElementById(`importStep${i}`);
            if (stepDiv) {
                stepDiv.style.display = i === step ? 'block' : 'none';
            }
        }
    }

    /**
     * 清除选择的文件
     */
    clearImportFile() {
        document.getElementById('importFileInput').value = '';
        document.getElementById('fileInfo').style.display = 'none';
        this.importData = null;
    }

    /**
     * 完成导入
     */
    async finishImport() {
        document.getElementById('importModal').style.display = 'none';
        this.importData = null;
        
        // 重新加载书签列表
        await this.loadBookmarks();
        
        // 触发更新事件
        window.dispatchEvent(new CustomEvent('bookmarksUpdated'));
    }

    /**
     * 格式化文件大小
     */
    formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // ========== 批量操作功能 ==========

    /**
     * 切换批量选择模式
     */
    toggleBatchMode() {
        this.batchMode = !this.batchMode;
        this.selectedBookmarks.clear();
        
        const btn = document.getElementById('batchModeBtn');
        const batchActions = document.getElementById('batchActions');
        
        if (this.batchMode) {
            if (btn) btn.innerHTML = '<i class="fas fa-times"></i> 取消批量';
            if (batchActions) batchActions.style.display = 'flex';
            // 禁用拖拽
            if (this.sortableInstance) {
                this.sortableInstance.option('disabled', true);
            }
        } else {
            if (btn) btn.innerHTML = '<i class="fas fa-check-square"></i> 批量操作';
            if (batchActions) batchActions.style.display = 'none';
            // 启用拖拽
            if (this.sortableInstance) {
                this.sortableInstance.option('disabled', false);
            }
        }
        
        this.renderBookmarks();
        this.updateBatchActionsUI();
    }

    /**
     * 切换单个收藏的选中状态
     */
    toggleBookmarkSelection(id) {
        if (this.selectedBookmarks.has(id)) {
            this.selectedBookmarks.delete(id);
        } else {
            this.selectedBookmarks.add(id);
        }
        this.updateBatchActionsUI();
    }

    /**
     * 全选/取消全选
     */
    toggleSelectAll() {
        const filtered = this.getFilteredBookmarks();
        
        if (this.selectedBookmarks.size === filtered.length) {
            // 已全选，取消全选
            this.selectedBookmarks.clear();
        } else {
            // 全选
            filtered.forEach(b => this.selectedBookmarks.add(b.id));
        }
        
        this.renderBookmarks();
        this.updateBatchActionsUI();
    }

    /**
     * 更新批量操作UI
     */
    updateBatchActionsUI() {
        const count = this.selectedBookmarks.size;
        const selectAllBtn = document.getElementById('selectAllBtn');
        const batchCountText = document.getElementById('batchCountText');
        
        if (selectAllBtn) {
            const filtered = this.getFilteredBookmarks();
            if (count === filtered.length && count > 0) {
                selectAllBtn.innerHTML = '<i class="fas fa-square"></i> 取消全选';
            } else {
                selectAllBtn.innerHTML = '<i class="fas fa-check-square"></i> 全选';
            }
        }
        
        if (batchCountText) {
            batchCountText.textContent = count > 0 ? `已选择 ${count} 项` : '未选择';
        }
        
        // 更新复选框状态
        document.querySelectorAll('.bookmark-checkbox').forEach(checkbox => {
            const id = parseInt(checkbox.dataset.id);
            checkbox.checked = this.selectedBookmarks.has(id);
        });
    }

    /**
     * 批量删除
     */
    async batchDelete() {
        if (this.selectedBookmarks.size === 0) {
            showNotification('请先选择要删除的收藏', 'warning');
            return;
        }

        const count = this.selectedBookmarks.size;
        const confirmed = await this.confirmBatchAction(`确定要删除 ${count} 个收藏吗？此操作不可撤销！`);
        
        if (!confirmed) return;

        const ids = Array.from(this.selectedBookmarks);
        let successCount = 0;
        let failCount = 0;

        for (const id of ids) {
            try {
                const response = await this.api.deleteBookmark(id);
                if (response && response.success) {
                    const index = this.bookmarks.findIndex(b => b.id === id);
                    if (index !== -1) {
                        this.bookmarks.splice(index, 1);
                    }
                    successCount++;
                } else {
                    failCount++;
                }
            } catch (error) {
                failCount++;
            }
        }

        this.selectedBookmarks.clear();
        this.renderBookmarks();
        this.updateStats();
        window.dispatchEvent(new CustomEvent('bookmarkDeleted'));

        if (failCount === 0) {
            showNotification(`成功删除 ${successCount} 个收藏`, 'success');
        } else {
            showNotification(`删除完成：成功 ${successCount} 个，失败 ${failCount} 个`, 'warning');
        }
    }

    /**
     * 批量移动
     */
    async batchMove() {
        if (this.selectedBookmarks.size === 0) {
            showNotification('请先选择要移动的收藏', 'warning');
            return;
        }

        const categoryId = await this.selectCategoryForBatch();
        if (categoryId === null) return;

        const ids = Array.from(this.selectedBookmarks);
        let successCount = 0;
        let failCount = 0;

        for (const id of ids) {
            try {
                const response = await this.api.moveBookmark(id, categoryId);
                if (response && response.success) {
                    const index = this.bookmarks.findIndex(b => b.id === id);
                    if (index !== -1) {
                        this.bookmarks[index] = response.data.bookmark;
                    }
                    successCount++;
                } else {
                    failCount++;
                }
            } catch (error) {
                failCount++;
            }
        }

        this.selectedBookmarks.clear();
        this.renderBookmarks();
        window.dispatchEvent(new CustomEvent('bookmarkMoved'));

        if (failCount === 0) {
            showNotification(`成功移动 ${successCount} 个收藏`, 'success');
        } else {
            showNotification(`移动完成：成功 ${successCount} 个，失败 ${failCount} 个`, 'warning');
        }
    }

    /**
     * 选择分组对话框（用于批量移动）
     */
    selectCategoryForBatch() {
        return new Promise((resolve) => {
            const modal = document.createElement('div');
            modal.className = 'modal';
            modal.style.display = 'block';
            
            // 获取分组列表 - 尝试多种方式
            let categories = [];
            if (typeof categoryManager !== 'undefined' && categoryManager) {
                categories = categoryManager.categories || [];
            } else if (window.categoryManager) {
                categories = window.categoryManager.categories || [];
            } else if (typeof navigationManager !== 'undefined' && navigationManager) {
                categories = navigationManager.categoryManager.categories || [];
            }
            
            console.log('批量移动-可用分组数量:', categories.length);
            
            modal.innerHTML = `
                <div class="modal-content">
                    <div class="modal-header">
                        <h3><i class="fas fa-folder"></i> 选择目标分组</h3>
                        <button class="modal-close" onclick="this.closest('.modal').remove()">
                            <i class="fas fa-times"></i>
                        </button>
                    </div>
                    <div class="modal-body">
                        <p class="modal-description">将选中的 ${this.selectedBookmarks.size} 个收藏移动到：</p>
                        <select id="batchMoveCategory" class="category-select" style="width: 100%; padding: 10px;">
                            <option value="">未分组</option>
                            ${categories.map(cat => `<option value="${cat.id}">${escapeHtml(cat.name)}</option>`).join('')}
                        </select>
                        ${categories.length === 0 ? '<p style="color: #999; margin-top: 10px; font-size: 0.9rem;">提示：请先创建分组</p>' : ''}
                        <div class="modal-buttons">
                            <button id="confirmBatchMoveBtn" class="btn-primary">
                                <i class="fas fa-check"></i> 确认移动
                            </button>
                            <button onclick="this.closest('.modal').remove()" class="btn-secondary">
                                取消
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            
            document.getElementById('confirmBatchMoveBtn').onclick = () => {
                const select = document.getElementById('batchMoveCategory');
                const categoryId = select.value || null;
                modal.remove();
                resolve(categoryId);
            };
            
            modal.querySelector('.modal-close').onclick = () => {
                modal.remove();
                resolve(null);
            };
        });
    }

    /**
     * 批量操作确认对话框
     */
    confirmBatchAction(message) {
        return new Promise((resolve) => {
            const modal = document.createElement('div');
            modal.className = 'modal';
            modal.style.display = 'block';
            
            modal.innerHTML = `
                <div class="modal-content">
                    <div class="modal-header">
                        <h3><i class="fas fa-exclamation-triangle"></i> 确认操作</h3>
                    </div>
                    <div class="modal-body">
                        <p>${message}</p>
                        <div class="modal-buttons">
                            <button id="confirmBtn" class="btn-danger">
                                <i class="fas fa-check"></i> 确认
                            </button>
                            <button id="cancelBtn" class="btn-secondary">
                                取消
                            </button>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.appendChild(modal);
            
            document.getElementById('confirmBtn').onclick = () => {
                modal.remove();
                resolve(true);
            };
            
            document.getElementById('cancelBtn').onclick = () => {
                modal.remove();
                resolve(false);
            };
        });
    }
}

// 导出供其他模块使用
if (typeof module !== 'undefined' && module.exports) {
    module.exports = BookmarkManager;
}

